#!/bin/bash -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$DIR"
source "$DIR/environment/util.sh"

# this should fix --break-system-packages not being available in older distros
export PIP_BREAK_SYSTEM_PACKAGES=1

function setup_virtualenv () {
    pushd $1 > /dev/null
    echo "Setting up virtualenv for: $1"

    # remove old virtualenv
    if [ -d ve3 ]; then
        rm -rf ve3
    fi

    python3 -m venv ve3 || exit 1
    source ve3/bin/activate
    pip install -r requirements.txt || exit 1
    deactivate

    popd > /dev/null
}

function print_help () {
  echo "Usage: $0 [--skip-prep-testing] [--ci]"
  echo "  --skip-prep-testing: Skip the preparation of the testing environment"
  echo "  --ci: Run the tests in CI mode"
}

ci=false
prep_testing=true
while(($#)); do
    case "$1" in
      --skip-prep-testing)
          shift
          prep_testing=false
      ;;
      --ci)
          shift
          ci=true
      ;;
      *)
          # unknown option
          echo "Invalid argument provided: $1"
          print_help
          exit 1
      ;;
    esac
done

DISTRO=$(operating_system)

# Fix for centos 7 during release
if [[ "$ci" == "false" ]]; then
  if [ "${DISTRO}" = "debian-11" ]; then
    if python3 -m pip show virtualenv >/dev/null 2>/dev/null; then
      python3 -m pip uninstall -y virtualenv
    fi
    python3 -m pip install virtualenv
  fi
fi

if [[ "$prep_testing" == "true" ]]; then
  setup_virtualenv tests
  cd tests
  ./setup.sh
  cd ..
fi
